import requests
import os
# from plotly.graph_objs import Bar
from plotly import offline

# 17.2 使用Plotly可视化仓库
"""
17.2.4 深入了解
[Plotly](https://plotly.com/python/)
[GitHub API](https://docs.github.com/en/rest)
"""
url = 'https://api.github.com/search/repositories?q=language:python&sort=stars'
headers = {'Accept': 'application/vnd.github.star+json'}
r = requests.get(url, headers=headers)
# print(f"Status code: {r.status_code}")
response_dict = r.json()
# print(response_dict.keys())
# print(f"Total repositories: {response_dict['total_count']}")
repo_dicts = response_dict['items']
# print(f"Repositories returned: {len(repo_dicts)}")

# 17.2.3 添加链接
# repo_names, stars = [], []
# 17.2.2 添加自定义工具提示
# labels = []
# 17.2.2 - end
repo_links, stars, labels = [], [], []
# 17.2.3 - end

for repo_dict in repo_dicts:
    # 17.2.3 添加链接
    # repo_names.append(repo_dict['name'])
    repo_name = repo_dict['name']
    repo_url = repo_dict['html_url']
    repo_link = f"<a href='{repo_url}'>{repo_name}</a>"
    repo_links.append(repo_link)
    # 17.2.3 - end
    stars.append(repo_dict['stargazers_count'])
    # 17.2.2 添加自定义工具提示
    owner = repo_dict['owner']['login']
    description = repo_dict['description']
    label = f"{owner}<br />{description}"
    labels.append(label)

data = [{
    'type': 'bar',
    'x': repo_links,
    'y': stars,
    # 17.2.2 添加自定义工具提示
    'hovertext': labels,
    # 17.2.2 - end
    # 17.2.1 改进图表样式
    'marker': {
        'color': 'rgb(60,100,150)',
        'line': {
            'width': 1.5,
            'color': 'rgb(25, 25, 25)'
        },
    },
    'opacity': 0.6,
    # 17.2.1 - end
}]

my_layout = {
    'title': 'GitHub 上最受欢迎的Python项目',
    # 17.2.1 改进图表样式
    'titlefont': {
        'size': 28
    },
    'xaxis': {
        'title': 'Repository',
        'titlefont': {
            'size': 24
        },
        'tickfont': {
            'size': 14
        },
    },
    'yaxis': {
        'title': 'Stars',
        'titlefont': {
            'size': 24
        },
        'tickfont': {
            'size': 14
        },
    },
    # 17.2.1 - end
}

fig = {'data': data, 'layout': my_layout}
if not os.path.exists('output'):
    os.mkdir('output')

offline.plot(fig, filename='output/python_repos.html')
